use std::collections::HashMap;
use std::path::Path;
use std::fs;
use lazy_static::lazy_static;

fn get_dict() -> HashMap<char, String> {
    // 获取拼音映射表
    let mut dict = HashMap::new();
    let project_root = env!("CARGO_MANIFEST_DIR");
    let file_path = Path::new(project_root).join("dict.txt");
    let content = fs::read_to_string(file_path).unwrap();
    for line in content.lines() {
        let info: Vec<&str> = line.split_whitespace().collect();
        if info.len() >= 2 {
            dict.insert(info[0].chars().next().unwrap(), info[1].to_string());
        }
    }
    dict
}

fn get_simple_ts_map() -> HashMap<char, char> {
    // 简单繁体字转换表
    let mut ts_map = HashMap::new();
    let project_root = env!("CARGO_MANIFEST_DIR");
    let file_path = Path::new(project_root).join("simple_st.txt");
    let content = fs::read_to_string(file_path).unwrap();
    for line in content.lines() {
        let info: Vec<&str> = line.split_whitespace().collect();
        if info.len() >= 2 {
            ts_map.insert(info[1].chars().next().unwrap(), info[0].chars().next().unwrap());
        }
    }
    ts_map
}

lazy_static! {
    static ref DICT: HashMap<char, String> = get_dict();
    static ref SIMPLE_TS_MAP: HashMap<char, char> = get_simple_ts_map();
}

fn capit(s: &str) -> String {
    s[0..1].to_uppercase() + &s[1..]
}

pub fn converter(input: &str) -> String {
    let input_string = input.to_string();
    let mut input_chars: Vec<char> = input_string.chars().collect();
    let simple_ts_map = &*SIMPLE_TS_MAP;
    // 预处理，将繁体字转换为简体字
    for i in 0..input_chars.len() {
        if simple_ts_map.contains_key(&input_chars[i]) {
            input_chars[i] = simple_ts_map[&input_chars[i]];
        }
    }
    let mut res = String::new();
    // 逐字的拼音转换，首字母大写
    for c in input_chars {
        if DICT.contains_key(&c) {
            if res.len() == 0 {
                res.push_str(&capit(&DICT[&c]));
            } else {
                res.push_str(" ");
                res.push_str(&DICT[&c]);
            }
        }
    }
    res
}
